import {
  TIM,
  COS,
  tim,
  emoji
} from '../../message/message.js';
const app = getApp();
const recorderManager = wx.getRecorderManager();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showChoosemore: false,
    sendMessage: '',
    store_name: '',
    emojiUrl: emoji.emojiUrl,
    emojiName: emoji.emojiName,
    emojiMap: emoji.emojiMap,
    ifshowEmoji: false,
    inputMode: 'keyboard',
    recordingTip: '长按进行录音',
    ifRecording: false,
    recordingStatu: '正在录音',
    title: '本地有客服',
    loading: false,
    color: '#FFFFFF',
    background: '#D50012',
    show: true,
    animated: false,
    keyboardHeight: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.store_name) {
      let store_name = options.store_name;
      this.setData({
        title: `${store_name}客服`
      })
    } else {
      this.setData({
        store_name: '本地有客服',
        title: '本地有客服'
      })
    }
    if (options.user_avatar) {
      this.setData({
        userAvatar: options.user_avatar
      })
    }
    this.setData({
      serverAvatar: options.avatar
    })
    let self = this;
    if (options.conversation_id) {
      let conversationID = options.conversation_id;
      this.getMessageList(conversationID);
      this.readMessage(conversationID);
      this.setData({
        conversationID
      });
    } else {
      this.userLogin();
      tim.on(TIM.EVENT.SDK_READY, function () {
        let conversationID;
        wx.getStorage({
          key: 'username',
          success: resu => {
            wx.getStorage({
              key: resu.data,
              success: res => {
                conversationID = res.data;
                self.setData({
                  conversationID
                });
                self.getMessageList(conversationID);
                self.readMessage(conversationID);
              }
            })
          }
        })
        
      });
    }
    this.setData({
      scrollHeight: app.globalData.wh
    })
  },
  userLogin: function () {
    let self = this;
    let userP = new Promise((resolve, reject) => {
      wx.getStorage({
        key: 'username',
        success: res => {
          resolve(res.data)
        },
        fail: () => {
          reject(Error('未登录'))
        }
      })
    })
    userP
      .then((username) => {
        return new Promise((resolve, reject) => {
          wx.getStorage({
            key: 'key',
            success: res => {
              let user = {
                username: username,
                key: res.data
              }
              resolve(user)
            },
            fail: () => {
              reject(Error('未登录'))
            }
          })
        })
      }).catch(error => {
        console.error(error)
      })
      .then((user) => {
        return new Promise((resolve, reject) => {
          wx.request({
            url: `${app.globalData.ApiUrl}/index.php?act=member_index&op=kefu&key=${user.key}`,
            method: 'GET',
            success: res => {
              if (res.data.code == 200) {
                self.setData({
                  userAvatar: res.data.datas.avatar
                })
                user.userSig = res.data.datas.user_sign
                resolve(user)
              } else {
                wx.showToast({
                  title: '该功能完善中',
                  icon: 'none'
                })
                setTimeout(() => {
                  wx.switchTab({
                    url: '../index/index'
                  })
                }, 1500);
                reject(Error(res.data.error))
              }
            }
          })
        })
      })
      .catch(error => {
        console.error(error)
      })
      .then((user) => {
        return tim.login({
          userID: user.username,
          userSig: user.userSig
        });
      })
      .then(imResponse => {
        console.log(imResponse)
      })
      .catch(imError => {
        console.warn('login error:', imError);
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  onMessageReceived: function () {
    this.getMessageList(this.data.conversationID)
  },
  readMessage: function (conversationID) {
    // 将某会话下所有未读消息已读上报
    let promise = tim.setMessageRead({
      conversationID: conversationID
    });
    promise.then(function (imResponse) {
      // 已读上报成功
    }).catch(function (imError) {
      // 已读上报失败
      console.warn('setMessageRead error:', imError);
    });
  },
  getMessageList: function (conversationID) {
    let self = this;
    let promise = tim.getMessageList({
      conversationID: conversationID,
      count: 15
    });
    promise.then(function (imResponse) {
      const messageList = imResponse.data.messageList; // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      self.setData({
        messageList,
        nextReqMessageID,
        isCompleted
      })
      self.detailEmojis();
      const query = wx.createSelectorQuery();
      query.select('.msg-detail-container').boundingClientRect(res => {
        self.setData({
          scrollContainerHeight: res.height
        })
      })
      query.exec();
    });
  },
  getMoreMessage: function () {
    let self = this;
    let nextReqMessageID = this.data.nextReqMessageID;
    if (!this.data.isCompleted) {
      // 下拉查看更多消息
      let promise = tim.getMessageList({
        conversationID: this.data.conversationID,
        nextReqMessageID,
        count: 15
      });
      promise.then(function (imResponse) {
        wx.showToast({
          title: '更新成功',
          icon: 'none'
        })
        const messageList = imResponse.data.messageList; // 消息列表。
        const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
        const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
        self.setData({
          messageList: messageList.concat(self.data.messageList),
          nextReqMessageID,
          isCompleted,
        })
        self.detailEmojis();
      });
    } else {
      wx.showToast({
        title: '没有更多啦',
        icon: 'none'
      })
    }
  },
  detailEmojis: function () {
    var reg = /\[([^\[\]]+)\]/g;
    let messageList = this.data.messageList;
    let messageText = '';
    let arrTmpl;
    let arr;
    let newArr;
    for (let i = 0; i < messageList.length; i++) {
      if (messageList[i].type == 'TIMTextElem') {
        messageText = messageList[i].payload.text;
        if (messageText) {
          if (messageText.match(reg)) {
            arrTmpl = messageText.match(reg).toString();
          }
          arr = messageText.split(reg);
          newArr = arr.filter(function (value) {
            return value != ''
          })
        }
        let virtualDom = [];
        for (let j = 0; j < newArr.length; j++) {
          if (!arrTmpl || arrTmpl.indexOf(newArr[j]) < 0) {
            virtualDom[j] = {
              name: 'span',
              text: newArr[j]
            }
          } else {
            virtualDom[j] = {
              name: 'img',
              src: this.data.emojiUrl + this.data.emojiMap[`[${newArr[j]}]`]
            }
          }
          messageList[i].virtualDom = virtualDom;
        }
      }
    }
    this.setData({
      messageList
    })
  },
  chooseMore: function (e) {
    let self = this;
    let statu = e.currentTarget.dataset.statu;
    if (statu == 'open') {
      this.setData({
        showChoosemore: true
      })
      let query = wx.createSelectorQuery();
      query.select('.chat-choose-more').boundingClientRect();
      query.exec(res => {
        self.setData({
          keyboardHeight: res[0].height
        })
        wx.pageScrollTo({
          scrollTop: res[0].height,
          duration: 200
        })
      })
    } else {
      this.setData({
        showChoosemore: false,
        keyboardHeight: 0
      })
    }
    this.setData({
      ifshowEmoji: false
    })
  },
  showEmojis: function () {
    let self = this;
    if (!this.data.ifshowEmoji) {
      this.setData({
        ifshowEmoji: !this.data.ifshowEmoji,
      })
      let query = wx.createSelectorQuery();
      query.select('.emojis').boundingClientRect();
      query.exec(res => {
        self.setData({
          keyboardHeight: res[0].height
        })
        wx.pageScrollTo({
          scrollTop: res[0].height,
          duration: 200
        })
      })
    }
  },
  messageInput: function (e) {
    this.setData({
      sendMessage: e.detail.value
    })
  },
  messageConfirm: function () {
    let self = this;
    var message = tim.createTextMessage({
      to: '本地有客服',
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        text: this.data.sendMessage
      }
    });

    this.setData({
      conversationID: message.conversationID
    })
    wx.getStorage({
      key: 'username',
      success: res => {
        wx.setStorage({
          key: res.data,
          data: message.conversationID
        })
      }
    })
    // 2. 发送消息
    let promise = tim.sendMessage(message);
    promise.then(function (imResponse) {
      // 发送成功
      self.getMessageList(self.data.conversationID);
      self.setData({
        sendMessage: ''
      })
    }).catch(function (imError) {
      // 发送失败
      console.warn('sendMessage error:', imError);
    });
  },
  chooseImages: function (e) {
    let self = this;
    let type = e.currentTarget.dataset.type;
    wx.chooseImage({
      sourceType: [type], // 从相册选择
      count: 1, // 只选一张，目前 SDK 不支持一次发送多张图片
      success: res => {
        // 2. 创建消息实例，接口返回的实例可以上屏
        let message = tim.createImageMessage({
          to: '本地有客服',
          conversationType: TIM.TYPES.CONV_C2C,
          payload: {
            file: res
          },
          onProgress: function (event) {
            console.log('file uploading:', event)
          }
        });
        // 3. 发送图片
        let promise = tim.sendMessage(message);
        promise.then(function (imResponse) {
          // 发送成功
          self.getMessageList(self.data.conversationID);
          self.setData({
            showChoosemore: false,
            keyboardHeight: 0
          })
        }).catch(function (imError) {
          // 发送失败
          console.warn('sendMessage error:', imError);
        });
      }
    })
  },
  chooseEmoji: function (e) {
    let index = e.currentTarget.dataset.index;
    let emojiText = this.data.emojiName[index];
    let sendMessage = this.data.sendMessage + emojiText
    this.setData({
      sendMessage
    })
  },
  changeMode: function (e) {
    let mode = e.currentTarget.dataset.mode;
    this.setData({
      inputMode: mode
    })
  },
  startRecord: function (e) {
    let self = this;
    // 录音部分参数
    const recordOptions = {
      duration: 60000, // 录音的时长，单位 ms，最大值 600000（10 分钟）
      sampleRate: 44100, // 采样率
      numberOfChannels: 1, // 录音通道数
      encodeBitRate: 192000, // 编码码率
      format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
    };
    recorderManager.start(recordOptions);
    recorderManager.onStart(() => {
      self.setData({
        ifRecording: true
      })
    });
    wx.getSetting({
      success: res => {
        console.log(res)
      }
    })
    recorderManager.onInterruptionBegin(() => {
      console.log('interruptionBegin')
      recorderManager.pause()
    })
    recorderManager.onInterruptionEnd(() => {
      console.log('interruptionEnd')
      recorderManager.resume()
    })
    //错误回调
    recorderManager.onError((res) => {
      wx.showToast({
        title: '录音失败',
        icon: 'none'
      })
    })
    this.setData({
      recordStartPoint: e.changedTouches[0].pageY
    })
  },
  stopRecord: function () {
    let self = this;
    if (this.data.moveY > 118) {
      this.setData({
        ifRecording: false,
        recordingStatu: '正在录音'
      })
      recorderManager.stop();
      recorderManager.onStop(res => {
        self.data.moveY = 0
        return false
      })
      return false;
    }
    recorderManager.stop()
    recorderManager.onStop(res => {
      self.setData({
        ifRecording: false
      })
      // 创建消息实例，接口返回的实例可以上屏
      if (res.duration - 1000 >= 0) {
        const message = tim.createAudioMessage({
          to: '本地有客服',
          conversationType: TIM.TYPES.CONV_C2C,
          payload: {
            file: res
          }
        });
        // 发送消息
        let promise = tim.sendMessage(message);
        promise.then(function (imResponse) {
          // 发送成功
          self.getMessageList(self.data.conversationID);
        }).catch(function (imError) {
          // 发送失败
          console.warn('sendMessage error:', imError);
        });
      }
    })
  },
  cancelRecord: function (e) {
    let moveY = this.data.recordStartPoint - e.changedTouches[0].pageY;
    this.setData({
      moveY
    })
    if (moveY > 70 && moveY < 118) {
      this.setData({
        recordingStatu: '上滑可取消'
      })
    }
    if (moveY >= 118) {
      this.setData({
        recordingStatu: '松开手指，取消发送'
      })
    }
  },
  playAudio: function (e) {
    const innerAudioContext = wx.createInnerAudioContext();
    let url = e.currentTarget.dataset.url;
    innerAudioContext.autoplay = true;
    innerAudioContext.src = url;
    innerAudioContext.onPlay(() => {})
    innerAudioContext.onError((res) => {
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      })
    })
    innerAudioContext.onEnded((res) => {
      innerAudioContext.destroy();
    })
  },
  inputFocus: function (e) {
    let keyboardHeight = e.detail.height;
    this.setData({
      keyboardHeight,
      ifshowEmoji: false
    })
    wx.pageScrollTo({
      scrollTop: keyboardHeight,
      duration: 200
    })
  },
  inputBlur: function () {
    this.setData({
      keyboardHeight: 0
    })
  },
  previewImage: function (e) {
    let url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url]
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // if (this.data.store_name != '') {
    //   let promise = tim.logout();
    //   promise.then(function (imResponse) {
    //     console.log(imResponse.data); // 登出成功
    //   }).catch(function (imError) {
    //     console.warn('logout error:', imError);
    //   });
    // }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.store_name != '本地有客服') {
      let promise = tim.logout();
      promise.then(function (imResponse) {
        console.log(imResponse.data); // 登出成功
      }).catch(function (imError) {
        console.warn('logout error:', imError);
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})